﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Logs.Repository;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace mozhi.smarterp.Finance.Logs
{
    public class OperationLogRepository : EfCoreRepository<FinanceDbContext, OperationLog, Guid>, IOperationLogRepository
    {
        public OperationLogRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<OperationLog>> FindAsync(OperationLogPageQuery query)
        {
            var dbQuery = query.IncludeDetail ? DbContext.Set<OperationLog>().Include(x => x.Items).AsNoTracking() : DbContext.Set<OperationLog>().AsNoTracking();

            var logs = await dbQuery
                 .WhereIf(!query.ModuleCode.IsNullOrEmpty(), x => x.ModuleCode == query.ModuleCode)
                 .WhereIf(query.ObjectId.HasValue, x => x.ObjectId == query.ObjectId)
                 .OrderByDescending(x=>x.CreationTime)
                 .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                 .ToListAsync();

            return logs;
        }

        public async Task<int> GetCountAsync(OperationLogPageQuery query)
        {
            var count = await DbContext.Set<OperationLog>().AsNoTracking()
                 .WhereIf(!query.ModuleCode.IsNullOrEmpty(), x => x.ModuleCode == query.ModuleCode)
                 .WhereIf(query.ObjectId.HasValue, x => x.ObjectId == query.ObjectId)
                 .CountAsync();

            return count;
        }
    }
}
